# -*- coding: utf-8 -*-
"""
@Time: 2025/1/10 11:42
@Auth: Zhang Hongxing
@File: ocr_service.py
@Note: 【需求10】输入形式多样化服务
"""
import os
import json
import pytesseract
from PIL import Image
import pdfplumber
from datetime import datetime

def ocr_service():
    pass


# -*- coding: utf-8 -*-
"""
@Time: 2025/1/10 11:42
@Auth: Zhang Hongxing
@File: ocr_service.py
@Note: 【需求10】输入形式多样化服务
"""
# 【接口2.1.1】POST /essay/submit/text    # 提交作文文本
def upload_text(user_id, title, text):
    """
    将用户上传的作文标题和文本以JSON格式保存到用户的专属文件中，按照essay_id分类存储
    :param user_id: 用户ID
    :param title: 作文标题
    :param text: 作文文本
    :return: 保存成功返回(True, essay_id, version_id)，失败返回(False)
    """
    try:
        # 用户专属文件路径
        file_path = f'../data/raw/essay_data/{user_id}.json'

        # 如果文件不存在，创建一个新的JSON文件
        if not os.path.exists(file_path):
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump({}, f)  # 初始化为空字典

        # 读取现有数据
        with open(file_path, 'r', encoding='utf-8') as f:
            essays = json.load(f)

        # 初始化 essay_id 和 version_id
        essay_id = None
        version_id = 1

        # 查找是否有相同 title 的作文
        for eid, essay_data in essays.items():
            if essay_data["title"] == title:
                essay_id = int(eid)
                break

        # 如果找到相同 title 的作文，则计算新的 version_id
        if essay_id is not None:
            version_id = max(v["version_id"] for v in essays[str(essay_id)]["versions"]) + 1
        else:
            # 如果没有找到相同 title 的作文，则生成新的 essay_id
            essay_id = max(map(int, essays.keys()), default=0) + 1
            essays[str(essay_id)] = {
                "title": title,
                "versions": []
            }

        # 创建新的作文版本数据
        new_version = {
            "version_id": version_id,
            "text": text,
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }

        # 将新版本添加到相应的 essay_id 下面
        essays[str(essay_id)]["versions"].append(new_version)

        # 保存更新后的数据
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(essays, f, ensure_ascii=False, indent=4)

        return True, essay_id, version_id

    except Exception as e:
        print("【接口2.1.1】报错：", e)
        return False

# 【接口2.1.2】POST /essay/submit/file    # 提交作文图片/文件
BASE_FILE_DIR = "../data/raw/essay_file"
BASE_TEXT_DIR = "../data/raw/essay_data"

os.makedirs(BASE_FILE_DIR, exist_ok=True)
os.makedirs(BASE_TEXT_DIR, exist_ok=True)

def sanitize_filename(filename):
    """ 清理文件名，去除特殊字符，防止路径错误 """
    return "".join(c if c.isalnum() or c in (' ', '.', '_') else '_' for c in filename)

def upload_image(image_file, usr_id=0):
    """ 处理图片文件并进行 OCR 识别 """
    try:
        # 获取原始文件名并清理
        original_filename = sanitize_filename(image_file.filename)
        file_path = os.path.join(BASE_FILE_DIR, f"{usr_id}_{original_filename}")

        # 保存文件
        image_file.save(file_path)

        image = Image.open(image_file)
        recognized_text = pytesseract.image_to_string(image, lang='eng')

        return file_path, recognized_text.strip()
    except Exception as e:
        print("【接口2.1.2】上传图片报错：", e)
        return None, None


def upload_pdf(pdf_file, usr_id=0):
    """ 处理 PDF 文件并提取文本 """
    try:
        # 获取原始文件名并清理
        original_filename = sanitize_filename(pdf_file.filename)
        file_path = os.path.join(BASE_FILE_DIR, f"{usr_id}_{original_filename}")
        pdf_file.save(file_path)

        recognized_text = ""
        with pdfplumber.open(pdf_file) as pdf:
            for page in pdf.pages:
                recognized_text += page.extract_text() + "\n"

        return file_path, recognized_text.strip()
    except Exception as e:
        print("【接口2.1.2】上传PDF报错：", e)
        return None, None


def save_essay_text(user_id, title, text):
    """ 将作文文本以 JSON 格式存储 """
    try:
        file_path = f"{BASE_TEXT_DIR}/{user_id}.json"

        if not os.path.exists(file_path):
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump({}, f)

        with open(file_path, 'r', encoding='utf-8') as f:
            essays = json.load(f)

        essay_id = None
        version_id = 1

        # 查找是否已存在相同标题
        for eid, essay_data in essays.items():
            if essay_data["title"] == title:
                essay_id = int(eid)
                break

        # 计算 version_id
        if essay_id is not None:
            version_id = max(v["version_id"] for v in essays[str(essay_id)]["versions"]) + 1
        else:
            essay_id = max(map(int, essays.keys()), default=0) + 1
            essays[str(essay_id)] = {"title": title, "versions": []}

        # 生成新版本
        new_version = {
            "version_id": version_id,
            "text": text,
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        essays[str(essay_id)]["versions"].append(new_version)

        # 写回 JSON
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(essays, f, ensure_ascii=False, indent=4)

        return True, essay_id, version_id

    except Exception as e:
        print("【接口2.1.2】保存作文文本报错：", e)
        return False, None, None
